package com.gmall.cart.interceptor;

import com.gmall.cart.config.JwtProperties;
import com.gmall.cart.pojo.UserInfo;
import com.gmall.common.utils.CookieUtils;
import com.gmall.common.utils.JwtUtils;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

@Data
@Component
@EnableConfigurationProperties(JwtProperties.class)
//@Scope("prototype")
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties properties;

    // private UserInfo userInfo;
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("==============preHandle================");

        // 通过cookie获取token和userKey
        String token = CookieUtils.getCookieValue(request, this.properties.getCookieName());
        String userKey = CookieUtils.getCookieValue(request, this.properties.getUserKey());
        // 不管 有没有登录都应该有userKey，如果有直接使用已有的即可，如果没有则生成一个放入cookie
        if (StringUtils.isBlank(userKey)){
            userKey = UUID.randomUUID().toString();
            CookieUtils.setCookie(request, response, this.properties.getUserKey(), userKey, 259200);
        }

        // 从token中解析出userId
        Long userId = null;
        if (StringUtils.isNotBlank(token)){
            Map<String, Object> map = JwtUtils.getInfoFromToken(token, properties.getPublicKey());
            userId = Long.valueOf(map.get("userId").toString());
        }

        // 假装已经获取了登录状态：userId=4 userKey=uuid
        // userInfo = new UserInfo(4L, UUID.randomUUID().toString());
        // request.setAttribute("userId", 4L);
        // request.setAttribute("userKey", UUID.randomUUID().toString());
        THREAD_LOCAL.set(new UserInfo(userId, userKey));

        return true;
    }

    public static UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("==============postHandle================");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 由于使用的是tomcat线程池，所以请求结束，线程并没有结束，必须手动调用remove方法，释放ThreadLocal中的资源，否则可能导致OOM
        THREAD_LOCAL.remove();
    }
}
